<template>
  <!--右键点击菜单-->
  <div
    class="context-menu"
    ref="listBox"
    :style="{
      left: left + 'px',
      top: top + 'px',
    }"
  >
    <div class="list-body" ref="listBody">
      <!--放 items-->
      <slot></slot>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'context-menu',
    components: {},
    props: {
      //控制显示和隐藏
      isShow: {
        type: Boolean,
        default: false,
      },
      left: {
        type: Number,
        default: 0,
      },
      top: {
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        timeFlag: null,
      }
    },
    methods: {
      handleShow() {
        //获得子元素的高度
        let sonDom = this.$refs.listBody

        let pDom = this.$refs.listBox
        this.$nextTick(() => {
          let height = sonDom.clientHeight
          let width = sonDom.clientWidth
          //如果是开启状态，则开启height
          if (this.isShow) {
            //开启的时候还要注意是否扎出界面外了
            pDom.style.height = height + 'px'

            //计算是否达到了高度的边界
            let bottomLength = document.body.clientHeight - this.top - height

            //计算是否到达了最右侧
            let sideLength = document.body.clientWidth - this.left - width

            if (bottomLength <= 0) {
              //如果到达高度边界了 那就top升高
              this.$emit('update:top', this.top - height)
            }

            if (sideLength <= 0) {
              //如果到达高度边界了 那就top升高
              this.$emit('update:left', this.left - width)
            }
          } else {
            pDom.style.height = '0'
          }
        })
      },
    },
    mounted() {
      //放置到body里
      document.body.appendChild(this.$el)

      this.handleShow()
    },
    watch: {
      isShow() {
        this.handleShow()
      },
    },
  }
</script>

<style scoped lang="scss">
  .context-menu {
    position: fixed;
    // width: 160px;
    width: 400px;
    top: 0;
    left: 0;
    z-index: 500;
    font-size: 14px;
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: 0 2px 15px -5px rgba(0, 0, 0, 0.4);
    transition: height 0.15s;
    overflow: hidden;
    .list-body {
    }
  }
</style>
